#将cookie保存到一个文件中
import urllib.request
from http.cookiejar import FileCookieJar,LWPCookieJar

filename = 'baidu2.txt'
#创建 cookiejar对象 跟文件交互 一般用LWPCookieJar
cookies = LWPCookieJar(filename=filename)
#创建cookie处理器
handler = urllib.request.HTTPCookieProcessor(cookies)

#创建打开器
opener = urllib.request.build_opener(handler)

headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
}

url = "http://www.baidu.com/"
req = urllib.request.Request(url,headers=headers)
response = opener.open(req)
print(response)
print(cookies)
cookies.save()